package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"os"
	"strings"
	"time"

	"oschina.net/justin.qin/baidu_sign/frisk"
	"oschina.net/justin.qin/baidu_sign/login"
)

func main() {
	//	log file
	path := os.Getenv("HOME")
	if _, err := os.Stat(path); err != nil {
		os.Mkdir(path, 0755)
	}
	var f *os.File
	var err error
	if _, err := os.Stat(path + "/baidu_sign_log.txt"); err != nil {
		f, err = os.Create(path + "/baidu_sign_log.txt")
	} else {
		f, err = os.OpenFile(path+"/baidu_sign_log.txt", os.O_RDWR|os.O_APPEND, 0644)
	}
	if err != nil {
		panic(err)
	}
	defer f.Close()

	f.WriteString(time.Now().String() + "\n")
	//	cookie file
	needLogin := false
	cookieJar, _ := cookiejar.New(nil)
	var cookies []*http.Cookie
	if _, err := os.Stat(path + "/baidu_sign_cookie.txt"); err == nil {
		rawCookie, _ := ioutil.ReadFile(path + "/baidu_sign_cookie.txt")
		rawCookieList := strings.Split(string(rawCookie), "\n")
		for _, rawCookieLine := range rawCookieList {
			rawCookieInfo := strings.SplitN(rawCookieLine, "=", 2)
			if len(rawCookieInfo) < 2 {
				continue
			}
			cookies = append(cookies, &http.Cookie{
				Name:  rawCookieInfo[0],
				Value: rawCookieInfo[1],
			})
		}
		url, _ := url.Parse("http://baidu.com")
		cookieJar.SetCookies(url, cookies)
		if login.GetLoginStatus(cookieJar) {
			needLogin = false
			fmt.Println("Using cookie saved in baidu_sign_cookie.txt...")
		}
	}
	//	login
	if needLogin {
		var username, password string
		bufferedReader := bufio.NewReader(os.Stdin)
		fmt.Print("Enter your Baidu ID: ")
		usernameByte, _, _ := bufferedReader.ReadLine()
		username = string(usernameByte)
		if username == "" {
			return
		}
		fmt.Print("Enter your Baidu Password: ")
		fmt.Scan(&password)
		if password == "" {
			return
		}
		result, loginErr := login.BaiduLogin(username, password, cookieJar, path)
		if loginErr == nil && result > 0 {
			fmt.Println("Successfully login")
			cookieStr := ""
			for _, cookie := range login.GetCookies(cookieJar) {
				cookieStr += cookie.Name + "=" + cookie.Value + "\n"
			}
			ioutil.WriteFile(path+"/baidu_sign_cookie.txt", []byte(cookieStr), 0644)

			fmt.Println("Your cookie has been written into baidu_sign_cookie.txt")
		} else {
			fmt.Println("Error while login:")
			fmt.Println(loginErr)
			time.Sleep(3 * time.Second)
			return
		}
	}

	//	// Start tieba sign
	//	fmt.Println("Fetching tieba list...")
	//	likedTiebaList, err := sign.GetLikedTiebaList(cookieJar)
	//	if err != nil {
	//		panic(err)
	//	}
	//	linkedList := list.New() // Create sign list
	//	for _, tieba := range likedTiebaList {
	//		linkedList.PushBack(tieba)
	//	}
	//	failedAttempts := make(map[int]int)
	//	for {
	//		listItem := linkedList.Front()
	//		if listItem == nil {
	//			break
	//		}
	//		linkedList.Remove(listItem)
	//		tieba := listItem.Value.(sign.LikedTieba)
	//		status, message, exp := sign.TiebaSign(tieba, cookieJar)
	//		f.WriteString(fmt.Sprintf("%s\t%d: %s\tEXP+%d\n", common.ToUtf8(tieba.Name), status, message, exp))
	//		if exp > 0 || status == 1 {
	//			time.Sleep(2 * time.Second)
	//		}
	//		if status == 1 {
	//			failedAttempts[tieba.TiebaId]++
	//			if failedAttempts[tieba.TiebaId] <= 5 {
	//				linkedList.PushBack(tieba) // push failed items back to list
	//			}
	//		}
	//	}
	//	time.Sleep(2 * time.Second)
	//	f.Sync()

	frisk.Top(cookieJar)
	f.Sync()
}
